Zip

The zip function makes an iterator that aggregates elements from each of the iterables into tuples. This means that the zip() function is supplied two iterables, and makes an iterator that calls the next() function on both iterables until one of them runs out (or both, if the iterables are of the same size) and returns tuples of (iter1, iter2, ... itern) until either iter1, iter2, or itern runs out of items.

zip(iterable1, iterable2, ....)

Let's see how this could be helpful.

Example 1 Basic zipping of two lists


In [3]:
lst1 = [1, 3, 4, 5]
lst2 = [6, 4, 3, 4]

combined = list(zip(lst1, lst2))

print(combined)


[(1, 6), (3, 4), (4, 3), (5, 4)]

Example 2 Adding another list to combine personal information


In [8]:
lst1 = ["Micah", "Joanna", "Rocky", "Mike"]
lst2 = [32, 21, 39, 19]
lst3 = ["F", "F", "M", "M"]

final_lst = list(zip(lst1, lst2, lst3))

print(final_lst)


[('Micah', 32, 'F'), ('Joanna', 21, 'F'), ('Rocky', 39, 'M'), ('Mike', 19, 'M')]